<?php
class Topic extends CI_Controller
{
	private $msg = array();
	
	function __construct()
	{
		parent::__construct();
                  if ($this->session->userdata("logged_in") != true) {
            header("location:./");
        }
		$this->load->model('topic_model', 'topic');
		$this->load->model('category_model', 'category');  
	}
	
	function index()
	{
		$this->viewAll();
	}
	
	function viewAll($sort= 'topic_news_date',$order = 'DESC', $name = '0', $category = '0',$sub_category = '0', $status = '-1',$limit = '5', $start = '0')
    {
        $name = urldecode($name);
        $category = urldecode($category);
        $sub_category = urldecode($sub_category);
        $status = urldecode($status);
        $filter = array(
            'sort'=>$sort,
            'order' => $order,
            'name' => $name,
            'category' => $category,
            'sub_category' => $sub_category,
            'status' => $status,
            'start' => $start, 
            'limit' => $limit
        );
        $data['topics'] = $this->topic->listAll($filter);
		$totaltopic = $this->topic->totaltopic($filter);
		$data['totaltopic'] = $totaltopic;
        $data['name'] = $name;
        $data['sort'] = $sort;
        $data['category_filter'] = $category;
        $data['sub_category_filter'] = $sub_category;
        $data['status'] = $status;
        $data['start'] = $start;
        $data['limit'] = $limit;
        $data['order'] = $order;
		
		 // phân trang cho app
        $this->load->library('pagination');
        $config['base_url'] = site_url("topic/viewAll/$sort/$order/$name/$category/$sub_category/$status/$limit");
        $config['total_rows'] = $totaltopic;
        $config['uri_segment'] = 10;
        $config['per_page'] =$limit;
        $config['full_tag_open'] = '<div class="pagination"><div class="links">';
        $config['full_tag_close'] = '</div></div>';
        $config['cur_tag_open'] = '<span class="active curved">';
        $config['cur_tag_close'] = '</span>';
        $config['num_tag_open'] = '';
        $config['num_tag_close'] = '';
        $config['next_link'] = 'Next';
        $config['prev_link'] = 'Previous';
        $config['prev_tag_open'] = '';
        $config['prev_tag_close'] = '';
        $config['last_tag_open'] = '';
        $config['last_tag_close'] = '';
        $this->pagination->initialize($config);
		
		if(isset($this->msg['error'])) $data['error'] = $this->msg['error'];
		if(isset($this->msg['success'])) $data['success'] = $this->msg['success'];
		$data['categorys'] = $this->category->listAll();
		$data['sub_categorys'] = $this->category->listSubCate();
		$data["username"] = $this->session->userdata('username');
		$this->load->view('default/admin/topic', $data);
	}
	/*
	 * add
	 */
	function add()
	{
		$data = array();
		if(isset($_POST['add'])) {
			$oldUmask = umask();
            umask(0);
			$cur = date('mY', microtime(true));
			$path = '/' . UPLOADFOLDER . '/topics/' . $cur . '/';
            if(!is_dir('.' . $path)) mkdir('.' . $path);
            umask($oldUmask);
			$config['upload_path'] = '.' . $path;
			$config['allowed_types'] = 'jpg|png|gif';
			$this->load->library('upload', $config);
			$image = "";
			if(!$this->upload->do_upload('topic_news_picture')) {
				// $data['error'] = $this->upload->display_errors();
			} else {
				$upload = $this->upload->data();
				$image = $path . $upload['file_name'];
                
                $imagesize = getimagesize('.'.$image);
                //Load thư viện xử lý ảnh để tạo thumbnail
                $this->load->library('image_lib');
                $config['source_image']	= '.'.$image;
                $config['width']    = $imagesize[0];
                $config['height']   = $imagesize[1];
                $config['quality']  = '100%';
                $this->image_lib->initialize($config);
                $this->image_lib->resize();
                $this->image_lib->clear();
			}
			$this->load->library('upload_multi');
	        $res = json_decode($this->upload_multi->do_upload());
	        if($res && $res->status!=false){
	            $list_images= $res->data;
	            $lists=array();
	            foreach ($list_images as $key => $value) {
	            	$lists[]='uploads/topics/' . $cur . '/' .$value->file_name;
	            }
	            $list = '';
	            if (count($lists) == 1)
	                $list = $lists[0];
	            else
	                $list = implode('@@', $lists);
	            $_POST['list_image_other'] = $list;
	        }
			unset($_POST['add']);
			$_POST['topic_news_picture'] = $image;
			$_POST['topic_news_date'] = time();
            $_POST['total_view'] = 1;
			$_POST['upload_by'] = $this->session->userdata('username');
			$this->topic->add($_POST);
			$data['success'] = 'Thêm mới topic thành công';
		}
		$data['categorys'] = $this->category->listAll();
		$data['sub_categorys'] = $this->category->listSubCate();
		$data["username"] = $this->session->userdata('username');
		$this->load->view('default/admin/topicadd', $data);
	}
	
	/*
	 * delete
	 */
	function delete()
	{
		if(isset($_POST['selected'])) {
			foreach($_POST['selected'] as $id)
				$this->topic->delete($id);
			$this->msg['success'] = 'Đã xóa topic (s) thành công';	
			
		}
		
		
		
		$this->viewAll();
		
	}
	function deletetopic()
	{
		$id = $this->input->post('id');
		$this->topic->delete($id);
		exit(json_encode(array(
            'msg' => 'Delete topic success!'
        )));
		
	}
	/*
	 * publish
	 */
	function publish()
	{
		if(isset($_POST['selected'])) {
			foreach($_POST['selected'] as $id)
				$this->topic->publish($id);
			$this->msg['success'] = 'Đã bật topic (s) thành công';	
		}
		$this->viewAll();
	}	
	
	/*
	 * unpublish
	 */
	function unPublish()
	{
		if(isset($_POST['selected'])) {
			foreach($_POST['selected'] as $id)
				$this->topic->unPublish($id);
			$this->msg['success'] = 'Đã tắt topic (s) thành công';	
		}
		$this->viewAll();
	}	
	
	// nhận request từ publishID() ở view topic
	function publishID() 
	{
		$topic_id = $this->input->post('id');
		$value = $this->input->post('value');
		
		if($value == 1) { 
			$this->topic->publish($topic_id);
			echo '<a href="javascript:;" onclick="publishID(' . $topic_id . ',0);">Bật</a>';			
		} else  {
			$this->topic->unpublish($topic_id);
			echo '<a href="javascript:;" onclick="publishID(' . $topic_id . ',1);">Tắt</a>';
		}
	}		
	
	/*
	 * edit
	 */
	function edit($id)
	{
		if(isset($_POST['update'])) {
            $oldUmask = umask();
            umask(0);
			$cur = date('mY', microtime(true));
			$path = '/' . UPLOADFOLDER . '/topics/' . $cur . '/';
            if(!is_dir('.' . $path)) mkdir('.' . $path);
            umask($oldUmask);
			$config['upload_path'] = '.' . $path;
			$config['allowed_types'] = 'jpg|png|gif';
			$this->load->library('upload', $config);
			$image = "";
			if(!$this->upload->do_upload('topic_news_picture')) {
				// $data['error'] = $this->upload->display_errors();
			} else {
				$upload = $this->upload->data();
				$image = $path . $upload['file_name'];
                
                $imagesize = getimagesize('.'.$image);
                //Load thư viện xử lý ảnh để tạo thumbnail
                $this->load->library('image_lib');
                $config['source_image']	= '.'.$image;
                $config['width']    = $imagesize[0];
                $config['height']   = $imagesize[1];
                $config['quality']  = '100%';
                $this->image_lib->initialize($config);
                $this->image_lib->resize();
                $this->image_lib->clear();
                $_POST['topic_news_picture'] = $image;
			}
			$this->load->library('upload_multi');
	        $res = json_decode($this->upload_multi->do_upload());
	        if($res && $res->status!=false){
	            $list_images= $res->data;
	            $list="";
	            foreach ($list_images as $key => $value) {
	            	$list .='@@'.base_url().'uploads/topics/' . $cur . '/' .$value->file_name;
	            }
	            $_POST['list_image_other'] = $list;
	        }
			unset($_POST['update']);
			$_POST['topic_news_date'] = microtime(true);
            $_POST['total_view'] = 1;
			$_POST['upload_by'] = $this->session->userdata('username');

			$this->topic->update($id, $_POST);
			
			$data['success'] = 'Cập nhật thành công';
		}
		$topicInfo = $this->topic->getInfo($id);
		$data['categorys'] = $this->category->listAll();
		// $data['sub_categorys'] = $this->category->listSubCate();
		$data['id'] = $id;
		$data['topic'] = $topicInfo;
		$data["username"] = $this->session->userdata('username');
		$this->load->view('default/admin/topicedit', $data);
	}
	function listSubByCate(){
		$cate_id= $this->input->post('category_id');
		$sub_categorys= $this->category->listSubCateById($cate_id);
		if($sub_categorys){
			$select = '<select name="sub_category_id">';
			foreach ($sub_categorys as $sub) {

	        $select .='<option value="'.$sub->sub_category_id.'">
	                            '.$sub->sub_category_name.'
	                            </option>';     
			}
			$select .= '</select>';
			echo $select;
		}else echo '';
	}
}
